package com.czxy.config;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

//声明配置类
@Configuration
public class MybatisConfig {

   //获取sessionFactory对象,
   @Bean
   @Resource
   public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
      //1.设置SQL
      // 通过工厂bean创建对象,对吼需要调用 getObject获取具体对象
      SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
      // 设置数据源
      factoryBean.setDataSource(dataSource);
      // 设置别名 要扫描的包
      factoryBean.setTypeAliasesPackage("com.czxy.domain");
      // 全局驼峰映射
      org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
      config.setMapUnderscoreToCamelCase(true);
      config.setLogImpl(StdOutImpl.class);
      factoryBean.setConfiguration(config);

      //2.插件配置 分页
      PageHelper pageHelper = new PageHelper();
      Properties pro = new Properties();
      pro.setProperty("dialect", "mysql");
      pro.setProperty("rowBoundsWithCount", "true");
      pageHelper.setProperties(pro);
      factoryBean.setPlugins(new Interceptor[]{pageHelper});
      //3. 通过工厂bean 获取 SQLSessionFactory

      return factoryBean.getObject();
   }

   /**
    *  设置要扫描的 mapper包 将创建好的XXXMapper对象存放到IOC容器中
    * @return
    */
   @Bean
   public MapperScannerConfigurer mapperScanner(){
      MapperScannerConfigurer configurer = new MapperScannerConfigurer();
      configurer.setBasePackage("com.czxy.dao");
      return configurer;
   }
}